package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"novel/models"
)

type NovelController struct {
	beego.Controller
}
type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NovelController) Add() {
	novel := c.GetString("novel")
	book := c.GetString("book")
	author := c.GetString("author")
	img := c.GetString("img")
	types := c.GetString("types")
	address := c.GetString("address")
	novels := models.Novel{
		Novel:   novel,
		Book:    book,
		Author:  author,
		Img:     img,
		Types:   types,
		Address: address,
	}
	err := models.DB.Create(&novels).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *NovelController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Novel{}).Count(&count)
	offset := (page - 1) * size
	var novels []models.Novel
	book := c.GetString("book")
	where := map[string]string{}
	if book != "" {
		where["book"] = book
	}
	err := models.DB.Offset(offset).Limit(size).Where(where).Find(&novels)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 400,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功",
			Data: novels,
		}
	}
}
func (c *NovelController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Novel{}, id).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
